package br.com.remedioCerto.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import br.com.remedioCerto.R;
import br.com.remedioCerto.receiver.BootReceive;
import br.com.remedioCerto.service.ValidadeAlarmeService;

public class Preferencia extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	
	SharedPreferences preferencias = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		
		addPreferencesFromResource(R.xml.preferencias);
	}
	
	@Override
	protected void onResume() {		
		super.onResume();
		preferencias = PreferenceManager.getDefaultSharedPreferences(this);
		preferencias.registerOnSharedPreferenceChangeListener(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		preferencias.unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		
		if ("alarme_validade".equals(key)) {
			
			boolean habilitado = preferencias.getBoolean(key, false);
			
			int flag = (habilitado ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
			ComponentName componente = new ComponentName(Preferencia.this, BootReceive.class);
			getPackageManager().setComponentEnabledSetting(componente, flag, PackageManager.DONT_KILL_APP);
			
			if (habilitado) {
				 Intent service = new Intent(this, ValidadeAlarmeService.class);
			     service.setAction(ValidadeAlarmeService.CREATE);
			     startService(service);
			} else {
				 Intent service = new Intent(this, ValidadeAlarmeService.class);
			     service.setAction(ValidadeAlarmeService.CANCEL);
			     startService(service);
			}
			
		} else if ("horario_alarme_validade".equals(key)) {
			
			 Intent cancel = new Intent(this, ValidadeAlarmeService.class);
		     cancel.setAction(ValidadeAlarmeService.CANCEL);
		     startService(cancel);

		     Intent create = new Intent(this, ValidadeAlarmeService.class);
		     create.setAction(ValidadeAlarmeService.CREATE);
		     startService(create);

		}
		
	}
}
